package com.mrs.gauss.interfaces.rest;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.mrs.gauss.common.ErrorCode;
import com.mrs.gauss.exception.BusinessException;
import com.mrs.gauss.interfaces.basicAuth.BasicAuthAccess;
import com.mrs.gauss.interfaces.basicAuth.HttpManager;
import lombok.extern.log4j.Log4j2;
import org.apache.http.client.HttpClient;

import java.io.*;
import java.util.*;

/**
 * HttpClient自带的HttpDelete方法是不支持上传body的，所以重写delete方法
 * 采集告警列表如果存在cpu和内存使用率存在告警 生成集群不正常标志文件：mrs_abnormal.ck，
 * 告警记录在：mrs_alarms_all.log
 *
 * @author wubai
 * @version [V100R002C30, 2025-04]
 * @since [OM 1.0]
 */
@Log4j2
public class MrsClusterHosts {
    //    private static final Logger log = LoggerFactory.getLogger(MrsClusterHosts.class);
    private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

    private static final String QUERY_HOSTS_LIST_URL = "/api/v3/hosts";
    private static HttpClient httpClient;

    /**
     * 程序运行入口
     */

    public List<Map> getHostsList() {
        log.info("Enter getHostsList");

        // 文件UserInfo.properties的路径
        String userFilePath = "./conf/UserInfo.properties";
        InputStream userInfo = null;
        ResourceBundle resourceBundle = null;
        List<Map> hostsList = null;

        try {
            File file = new File(userFilePath);
            if (!file.exists()) {
                log.error("The user info file doesn't exist.");
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "集群用户属性文件不存在");
            }
//            log.info("Get the web info and user info from file {} ", file);

            userInfo = new BufferedInputStream(new FileInputStream(file));
            resourceBundle = new PropertyResourceBundle(userInfo);

            // 获取用户名
            String userName = resourceBundle.getString("userName");
            if (userName == null || userName.isEmpty()) {
                log.error("The userName is empty.");
            }

            // 获取用户密码
            String password = resourceBundle.getString("password");
            if (password == null || password.isEmpty()) {
                log.error("The password is empty.");
            }

            String webUrl = resourceBundle.getString("webUrl");
//            log.info("The webUrl is : {}.", webUrl);

            // userTLSVersion是必备的参数，是处理jdk1.6服务端连接jdk1.8服务端时的重要参数，如果用户使用的是jdk1.8该参数赋值为空字符串即可
            String userTLSVersion = "";
            //已登录或session没过期 不再登录
            // 调用firstAccess接口完成登录认证
//            log.info("Begin to get httpclient and first access.");
            BasicAuthAccess authAccess = new BasicAuthAccess();
            httpClient = authAccess.loginAndAccess(webUrl, userName, password, userTLSVersion);
            HttpManager httpManager = new HttpManager();
            String operationName = "";
            String operationUrl = "";

            // 访问Manager接口完成查找Hosts列表
            operationName = "QueryHostsList";
            operationUrl = webUrl + QUERY_HOSTS_LIST_URL;
            String responseLineContent = httpManager.sendHttpGetRequest1(httpClient, operationUrl, operationName);
            hostsList = jsonToMaps(responseLineContent);
        } catch (FileNotFoundException e) {
            log.error("File not found exception.");
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } catch (Throwable e) {
            e.printStackTrace();
            log.error(e.getMessage());
        } finally {
            if (userInfo != null) {
                try {
                    userInfo.close();
                } catch (IOException e) {
                    log.error("IOException.");
                }
            }
        }
        // List<Map>
        return hostsList;
    }


    /**
     * 获取多台主机的instances,每个instants是一个List<StringBuilder>
     * 如主机1：[KrbServer[KerberosServer], KrbServer[KerberosAdmin]]
     *
     * @param json
     * @return
     * @throws IOException
     */
    public static List<Map> jsonToMaps(String json) throws IOException {
        Map map = OBJECT_MAPPER.readValue(json, Map.class);
        List<Map> hostsList = (List) (map.get("hosts"));  // [M1,M2,M3]
        ArrayList<List<Map>> inst_list = new ArrayList<>();//instances [[M1],[M2],[M3]]
        hostsList.stream().forEach(item -> inst_list.add((List<Map>) item.get("instances")));//instances [[M1],[M2],[M3]]
        //instances [[M1],[M2],[M3]]
        for (int i = 0; i < inst_list.size(); i++) {
            List<StringBuilder> inst_lists1 = new ArrayList<>();
            for (Map item1 : inst_list.get(i)) {
                StringBuilder sb = new StringBuilder(item1.get("serviceName").toString()).append("[").append(item1.get("roleName")).append("]");
                inst_lists1.add(sb); //如主机1：[KrbServer[KerberosServer], KrbServer[KerberosAdmin]]
            }
            hostsList.get(i).put("instances", inst_lists1);
        }
        return hostsList; // 里面的instances [[StringBuilder,StringBuilder,...],[...],[...]]
    }
}
